package com.abe.jetpack.helper

import android.support.annotation.IntDef
import com.google.gson.*
import java.lang.reflect.Type
import java.util.*
import java.util.regex.Pattern


object JsonHelper {
    //按照日期转换区分
    const val JSON_NORMAL: Int = 1//普通Gson
    const val JSON_C_SHAPE: Int = 2//C# gson

    @IntDef(JSON_NORMAL, JSON_C_SHAPE)
    @Retention(AnnotationRetention.SOURCE)
    internal annotation class JsonType

    fun gson(@JsonType type: Int): Gson {
        val builder = GsonBuilder()
        when (type) {
            JSON_C_SHAPE -> builder.registerTypeAdapter(Date::class.java, DateDeserializer())
        }
        return builder.serializeNulls().create()
    }

    internal class DateDeserializer : JsonDeserializer<Date> {
        @Throws(JsonParseException::class)
        override fun deserialize(json: JsonElement, typeOfT: Type,
                                 context: JsonDeserializationContext): Date {
            val jsonDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/"
            val pattern = Pattern.compile(jsonDateToMilliseconds)
            val matcher = pattern.matcher(json.asJsonPrimitive
                    .asString)
            val result = matcher.replaceAll("$2")
            return Date(result.toLong())
        }
    }
}